﻿// pages/team-orders/team-orders.js
Page({
  data: {
    loading: true,
    currentTab: 0, // 0: 可接订单, 1: 已接订单
    
    // 标签页配置
    tabs: [
      { key: 'available', name: '可接订单', icon: '📋' },
      { key: 'accepted', name: '已接订单', icon: '🏗️' }
    ],
    
    // 可接订单
    availableOrders: [],
    availableOrdersLoading: false,
    availableOrdersHasMore: true,
    availableOrdersPage: 1,
    availableOrdersTotal: 0,
    
    // 已接订单
    myOrders: [],
    myOrdersLoading: false,
    myOrdersHasMore: true,
    myOrdersPage: 1,
    myOrdersTotal: 0,
    
    // 筛选条件
    filters: {
      category: 'all',
      urgency: 'all',
      status: 'all'
    },
    
    // 选项
    urgencyOptions: [
      { key: 'all', name: '全部', color: '#666' },
      { key: 'low', name: '一般', color: '#52c41a' },
      { key: 'normal', name: '普通', color: '#1890ff' },
      { key: 'high', name: '紧急', color: '#fa8c16' },
      { key: 'urgent', name: '特急', color: '#f5222d' }
    ],
    
    statusOptions: [
      { key: 'all', name: '全部状态' },
      { key: 'waiting_team', name: '待接单' },
      { key: 'team_accepted', name: '已接单' },
      { key: 'surveying', name: '查勘中' },
      { key: 'designing', name: '设计中' },
      { key: 'quoted', name: '已报价' },
      { key: 'in_progress', name: '施工中' },
      { key: 'testing', name: '验收中' },
      { key: 'completed', name: '已完成' },
      { key: 'cancelled', name: '已取消' }
    ],
    
    // 状态统计数据
    statusStats: {},
    statsLoaded: false,
    
    // 队伍信息
    teamInfo: null,
    
    // 接单弹窗
    showAcceptModal: false,
    selectedOrder: null,
    acceptForm: {
      estimatedPrice: '',
      estimatedDays: '',
      notes: ''
    },
    
    // 状态更新弹窗
    showStatusModal: false,
    statusForm: {
      orderId: '',
      status: '',
      statusName: '',
      notes: '',
      images: []
    }
  },

  async onLoad(options) {
    console.log('🏗️ 施工队伍订单页面加载')
    
    // 检查登录状态
    const loginCheck = await this.checkLoginStatus()
    if (!loginCheck.success) {
      this.showLoginRequired()
      return
    }
    
    // 初始化数据
    await this.initData()
  },

  async onShow() {
    // 页面显示时刷新统计数据和当前标签页数据
    await this.loadOrderStats()
    await this.refreshCurrentTab()
  },

  async onPullDownRefresh() {
    await this.refreshCurrentTab()
    wx.stopPullDownRefresh()
  },

  async onReachBottom() {
    if (this.data.currentTab === 0) {
      await this.loadMoreAvailableOrders()
    } else {
      await this.loadMoreMyOrders()
    }
  },

  // 检查登录状态（使用宽松的检查方式）
  async checkLoginStatus() {
    try {
      console.log('🔐 检查登录状态...')
      
      // 首先检查本地登录状态
      const isLoggedIn = wx.getStorageSync('isLoggedIn')
      const userInfo = wx.getStorageSync('userInfo')
      
      if (!isLoggedIn || !userInfo || !userInfo.openid) {
        console.log('❌ 本地登录状态无效')
        return { success: false, error: '本地登录状态无效' }
      }
      
      console.log('✅ 本地登录状态有效')
      
      // 检查微信session（不阻塞，只记录）
      wx.checkSession({
        success: () => {
          console.log('✅ 微信session有效')
        },
        fail: () => {
          console.log('⚠️ 微信session已过期，但不影响使用')
        }
      })
      
      return { 
        success: true, 
        userInfo: userInfo,
        message: '登录状态有效'
      }
      
    } catch (error) {
      console.error('检查登录状态失败:', error)
      return { success: false, error: error.message }
    }
  },

  // 显示登录要求
  showLoginRequired() {
    wx.showModal({
      title: '需要登录',
      content: '请先登录后再查看订单信息',
      confirmText: '去登录',
      cancelText: '返回',
      success: (res) => {
        if (res.confirm) {
          wx.navigateTo({
            url: '/pages/profile/profile'
          })
        } else {
          wx.navigateBack()
        }
      }
    })
  },

  // 初始化数据
  async initData() {
    wx.showLoading({ title: '加载中...' })
    
    try {
      // 获取施工队伍信息
      const teamInfoResult = await wx.cloud.callFunction({
        name: 'teamOrderManager',
        data: {
          action: 'getTeamInfo'
        }
      })
      
      if (!teamInfoResult.result.success) {
        wx.hideLoading()
        wx.showModal({
          title: '提示',
          content: teamInfoResult.result.error || '您还没有注册施工队伍或尚未通过审核',
          confirmText: '去注册',
          cancelText: '返回',
          success: (res) => {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/team-registration/team-registration'
              })
            } else {
              wx.navigateBack()
            }
          }
        })
        return
      }
      
      this.setData({
        teamInfo: teamInfoResult.result.data
      })
      
      // 加载状态统计数据
      await this.loadOrderStats()
      
      // 加载订单数据
      await this.loadAvailableOrders()
      
      wx.hideLoading()
      this.setData({ loading: false })
      
    } catch (error) {
      wx.hideLoading()
      console.error('初始化数据失败:', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    }
  },

  // 加载订单状态统计
  async loadOrderStats() {
    try {
      console.log('📊 开始加载订单状态统计...')
      
      const result = await wx.cloud.callFunction({
        name: 'teamOrderManager',
        data: {
          action: 'getOrderStats'
        }
      })
      
      console.log('📡 云函数完整返回结果:', result)
      console.log('📡 result.result:', result.result)
      
      if (result.result && result.result.success) {
        console.log('✅ 状态统计加载成功:', result.result.data)
        const stats = result.result.data
        
        console.log('📊 完整统计数据:', stats)
        console.log('📊 totalMyOrders值:', stats.totalMyOrders)
        console.log('📊 准备设置myOrdersTotal为:', stats.totalMyOrders || 0)
        
        const updateData = {
          statusStats: stats,
          // 更新标签页显示的总数
          myOrdersTotal: stats.totalMyOrders || 0,
          statsLoaded: true
        }
        
        console.log('📊 准备setData的数据:', updateData)
        
        this.setData(updateData)
        
        console.log('📊 setData完成，验证数据:')
        console.log('  - myOrdersTotal:', this.data.myOrdersTotal)
        console.log('  - statsLoaded:', this.data.statsLoaded)
        console.log('  - statusStats:', this.data.statusStats)
        
        // 更新状态选项显示（添加数量）
        this.updateStatusOptionsWithCounts()
        
        // 强制触发页面更新
        this.$apply && this.$apply()
        
      } else {
        console.error('❌ 状态统计加载失败:', result.result ? result.result.error : '云函数调用失败')
        console.error('❌ 完整错误信息:', result)
      }
      
    } catch (error) {
      console.error('❌ 加载状态统计异常:', error)
      console.error('❌ 错误堆栈:', error.stack)
    }
  },

  // 更新状态选项显示（添加数量）
  updateStatusOptionsWithCounts() {
    const { statusStats } = this.data
    console.log('🔍 当前统计数据:', statusStats)
    
    const baseOptions = [
      { key: 'all', name: '全部状态', baseKey: 'totalMyOrders' },
      { key: 'waiting_team', name: '待接单', baseKey: 'waiting_team' },
      { key: 'team_accepted', name: '已接单', baseKey: 'team_accepted' },
      { key: 'surveying', name: '查勘中', baseKey: 'surveying' },
      { key: 'designing', name: '设计中', baseKey: 'designing' },
      { key: 'quoted', name: '已报价', baseKey: 'quoted' },
      { key: 'in_progress', name: '施工中', baseKey: 'in_progress' },
      { key: 'testing', name: '验收中', baseKey: 'testing' },
      { key: 'completed', name: '已完成', baseKey: 'completed' },
      { key: 'cancelled', name: '已取消', baseKey: 'cancelled' }
    ]
    
    const statusOptionsWithCounts = baseOptions.map(option => {
      const count = statusStats[option.baseKey] || 0
      return {
        ...option,
        name: `${option.name} (${count})`,
        count: count
      }
    })
    
    console.log('🔢 状态选项更新:', statusOptionsWithCounts)
    
    this.setData({
      statusOptions: statusOptionsWithCounts
    })
  },

  // 切换标签页
  onTabChange(e) {
    const index = e.currentTarget.dataset.index
    this.setData({ currentTab: index })
    
    if (index === 0) {
      // 可接订单
      if (this.data.availableOrders.length === 0) {
        this.loadAvailableOrders()
      }
    } else {
      // 已接订单
      if (this.data.myOrders.length === 0) {
        this.loadMyOrders()
      }
      // 切换到已接订单时刷新统计数据
      this.loadOrderStats()
    }
  },

  // 刷新当前标签页
  async refreshCurrentTab() {
    if (this.data.currentTab === 0) {
      await this.loadAvailableOrders()
    } else {
      await this.loadMyOrders()
    }
  },

  // 加载可接订单 - 优化版本（显示所有待接单状态）
  async loadAvailableOrders(loadMore = false) {
    if (this.data.availableOrdersLoading) return
    
    console.log('🔄 加载可接订单 (优化版本):', { loadMore, page: loadMore ? this.data.availableOrdersPage : 1 })
    
    this.setData({ availableOrdersLoading: true })
    
    try {
      const result = await wx.cloud.callFunction({
        name: 'teamOrderManager',
        data: {
          action: 'getAvailableOrders',
          page: loadMore ? this.data.availableOrdersPage : 1,
          pageSize: 10,
          filters: this.data.filters
        }
      })
      
      console.log('📋 云函数返回结果:', result.result)
      
      if (result.result.success) {
        const newOrders = result.result.data?.orders || []
        const total = result.result.data?.total || 0
        
        console.log(`📊 获取到 ${newOrders.length} 个可接订单，总共 ${total} 个`)
        
        // 处理订单数据，添加UI需要的字段
        const processedOrders = newOrders.map(order => {
          const processedOrder = {
            ...order,
            // 保持原有的 order.id 字段，不要覆盖为 _id
            publishedHours: this.calculateHours(order.createTime),
            acceptedHours: order.acceptTime ? this.calculateHours(order.acceptTime) : 0,
            serviceTypeLabel: order.serviceTypeLabel || order.serviceType || '未知服务',
            // 添加状态显示
            statusText: order.statusLabel || this.getStatusText(order.status),
            statusColor: this.getStatusColor(order.status),
            // 添加紧急程度显示
            urgencyText: this.getUrgencyText(order.urgency),
            urgencyColor: order.urgencyColor || this.getUrgencyColor(order.urgency),
            // 添加时间显示
            publishedTimeText: this.formatPublishedTime(order.publishedHours || this.calculateHours(order.createTime)),
            // 可接单标识
            canAcceptOrder: order.canAccept !== false
          }
          
          console.log(`  📋 ${processedOrder.id} - ${processedOrder.statusText} - ${processedOrder.serviceTypeLabel}`)
          
          return processedOrder
        })
        
        this.setData({
          availableOrders: loadMore ? [...this.data.availableOrders, ...processedOrders] : processedOrders,
          availableOrdersPage: loadMore ? this.data.availableOrdersPage + 1 : 2,
          availableOrdersHasMore: newOrders.length === 10,
          availableOrdersLoading: false,
          availableOrdersTotal: total
        })
        
        // 显示加载结果
        if (!loadMore && processedOrders.length === 0) {
          wx.showToast({
            title: '暂无可接订单',
            icon: 'none',
            duration: 2000
          })
        } else if (!loadMore) {
          console.log(`✅ 成功加载 ${processedOrders.length} 个可接订单`)
        }
        
      } else {
        console.error('❌ 加载可接订单失败:', result.result.error)
        wx.showToast({
          title: result.result.error || '加载失败',
          icon: 'none'
        })
        this.setData({ availableOrdersLoading: false })
      }
      
    } catch (error) {
      console.error('❌ 加载可接订单异常:', error)
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none'
      })
      this.setData({ availableOrdersLoading: false })
    }
  },
  
  // 获取状态显示文本（与用户端完全对应）
  getStatusText(status) {
    const statusMap = {
      // 主要状态（与用户端订单标签页完全对应）
      'waiting_team': '待接单',
      'team_accepted': '已接单',
      'surveying': '查勘中',
      'designing': '设计中',
      'quoted': '已报价',
      'in_progress': '施工中',
      'testing': '验收中',
      'completed': '已完成',
      'cancelled': '已取消',
      
      // 兼容旧状态
      'pending': '待接单',
      'accepted': '已接单',
      'confirmed': '已接单',
      'team_preparing': '已接单',
      'team_on_site': '施工中',
      'paused': '施工中',
      'rejected': '已取消',
      'reassigning': '待接单'
    }
    return statusMap[status] || status
  },
  
  // 获取状态颜色（与用户端完全对应）
  getStatusColor(status) {
    const colorMap = {
      // 主要状态（与用户端statusMap完全对应）
      'waiting_team': '#FF6B35',     // 待接单 - 橙色
      'team_accepted': '#2196F3',    // 已接单 - 蓝色
      'surveying': '#9C27B0',        // 查勘中 - 紫色
      'designing': '#673AB7',        // 设计中 - 深紫色
      'quoted': '#3F51B5',           // 已报价 - 靛蓝色
      'in_progress': '#2196F3',      // 施工中 - 蓝色
      'testing': '#00BCD4',          // 验收中 - 青色
      'completed': '#4CAF50',        // 已完成 - 绿色
      'cancelled': '#F44336',        // 已取消 - 红色
      
      // 兼容旧状态
      'pending': '#FF6B35',
      'accepted': '#2196F3',
      'confirmed': '#2196F3',
      'team_preparing': '#2196F3',
      'team_on_site': '#2196F3',
      'paused': '#FF9800',
      'rejected': '#F44336',
      'reassigning': '#FF9800'
    }
    return colorMap[status] || '#666666'
  },
  
  // 获取紧急程度文本
  getUrgencyText(urgency) {
    const urgencyMap = {
      'low': '一般',
      'normal': '普通',
      'high': '紧急', 
      'urgent': '特急',
      'emergency': '特急'
    }
    return urgencyMap[urgency] || '普通'
  },
  
  // 获取紧急程度颜色
  getUrgencyColor(urgency) {
    const colorMap = {
      'low': '#52c41a',
      'normal': '#1890ff',
      'high': '#fa8c16',
      'urgent': '#f5222d', 
      'emergency': '#f5222d'
    }
    return colorMap[urgency] || '#666666'
  },
  
  // 格式化发布时间
  formatPublishedTime(hours) {
    if (hours < 1) {
      return '刚发布'
    } else if (hours < 24) {
      return `${hours}小时前`
    } else {
      const days = Math.floor(hours / 24)
      return `${days}天前`
    }
  },

  // 加载已接订单
  async loadMyOrders(loadMore = false) {
    if (this.data.myOrdersLoading) return
    
    this.setData({ myOrdersLoading: true })
    
    try {
      const result = await wx.cloud.callFunction({
        name: 'teamOrderManager',
        data: {
          action: 'getMyOrders',
          page: loadMore ? this.data.myOrdersPage : 1,
          pageSize: 10,
          filters: this.data.filters
        }
      })
      
      if (result.result.success) {
        const newOrders = result.result.data?.orders || []
        const total = result.result.data?.total || 0
        
        // 处理订单数据，添加UI需要的字段
        const processedOrders = newOrders.map(order => ({
          ...order,
          // 保持原有的 order.id 字段，不要覆盖为 _id
          publishedHours: this.calculateHours(order.createTime),
          acceptedHours: order.acceptTime ? this.calculateHours(order.acceptTime) : 0,
          serviceTypeLabel: order.serviceType || '未知服务'
        }))
        
        this.setData({
          myOrders: loadMore ? [...this.data.myOrders, ...processedOrders] : processedOrders,
          myOrdersPage: loadMore ? this.data.myOrdersPage + 1 : 2,
          myOrdersHasMore: newOrders.length === 10,
          myOrdersLoading: false,
          myOrdersTotal: total
        })
      } else {
        console.error('加载已接订单失败:', result.result.error)
        wx.showToast({
          title: '加载失败',
          icon: 'none'
        })
        this.setData({ myOrdersLoading: false })
      }
      
    } catch (error) {
      console.error('加载已接订单异常:', error)
      wx.showToast({
        title: '网络错误',
        icon: 'none'
      })
      this.setData({ myOrdersLoading: false })
    }
  },

  // 加载更多可接订单
  async loadMoreAvailableOrders() {
    if (this.data.availableOrdersHasMore && !this.data.availableOrdersLoading) {
      await this.loadAvailableOrders(true)
    }
  },

  // 加载更多已接订单
  async loadMoreMyOrders() {
    if (this.data.myOrdersHasMore && !this.data.myOrdersLoading) {
      await this.loadMyOrders(true)
    }
  },

  // 跳转到订单详情
  viewOrderDetail(e) {
    const orderId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/team-order-detail/team-order-detail?id=${orderId}`
    })
  },

  // 显示接单弹窗
  showAcceptOrder(e) {
    const order = e.currentTarget.dataset.order
    this.setData({
      showAcceptModal: true,
      selectedOrder: order,
      acceptForm: {
        estimatedPrice: '',
        estimatedDays: '',
        notes: ''
      }
    })
  },

  // 隐藏接单弹窗
  hideAcceptModal() {
    this.setData({
      showAcceptModal: false,
      selectedOrder: null
    })
  },

  // 表单输入
  onAcceptFormInput(e) {
    const { field } = e.currentTarget.dataset
    const { value } = e.detail
    
    this.setData({
      [`acceptForm.${field}`]: value
    })
  },

  // 确认接单
  async confirmAcceptOrder() {
    const { selectedOrder, acceptForm } = this.data
    
    if (!acceptForm.estimatedPrice) {
      wx.showToast({
        title: '请填写预估价格',
        icon: 'none'
      })
      return
    }
    
    if (!acceptForm.estimatedDays) {
      wx.showToast({
        title: '请填写预估工期',
        icon: 'none'
      })
      return
    }
    
    wx.showLoading({ title: '接单中...' })
    
    try {
      const result = await wx.cloud.callFunction({
        name: 'teamOrderManager',
        data: {
          action: 'acceptOrder',
          orderId: selectedOrder.id,
          estimatedPrice: parseFloat(acceptForm.estimatedPrice),
          estimatedDays: acceptForm.estimatedDays,
          notes: acceptForm.notes
        }
      })
      
      if (result.result.success) {
        wx.hideLoading()
        wx.showToast({
          title: '接单成功',
          icon: 'success'
        })
        
        this.hideAcceptModal()
        
        // 刷新统计数据
        await this.loadOrderStats()
        
        // 刷新数据
        await this.refreshCurrentTab()
        
      } else {
        wx.hideLoading()
        wx.showToast({
          title: result.result.error || '接单失败',
          icon: 'none'
        })
      }
      
    } catch (error) {
      wx.hideLoading()
      console.error('接单失败:', error)
      wx.showToast({
        title: '网络错误',
        icon: 'none'
      })
    }
  },

  // 显示状态更新弹窗
  showUpdateStatus(e) {
    console.log('🔄 点击更新状态按钮 (列表页)')
    const order = e.currentTarget.dataset.order
    console.log('📋 选中的订单:', order)
    console.log('📋 当前订单状态:', order?.status)
    
    if (!order) {
      console.error('❌ 未获取到订单信息')
      wx.showToast({
        title: '获取订单信息失败',
        icon: 'none'
      })
      return
    }

    // 根据当前状态动态生成可选状态（与用户端状态流转对应）
    let statusOptions = []
    
    switch(order.status) {
      // 兼容旧状态
      case 'accepted':
      case 'team_accepted':
        statusOptions = [
          { key: 'surveying', name: '开始查勘' }
        ]
        break
      case 'surveying':
        statusOptions = [
          { key: 'designing', name: '开始设计' }
        ]
        break
      case 'designing':
        statusOptions = [
          { key: 'quoted', name: '完成报价' }
        ]
        break
      case 'quoted':
        statusOptions = [
          { key: 'in_progress', name: '开始施工' }
        ]
        break
      case 'in_progress':
        statusOptions = [
          { key: 'testing', name: '开始验收' }
        ]
        break
      case 'testing':
        statusOptions = [
          { key: 'completed', name: '完成订单' }
        ]
        break
      case 'waiting_team':
        // 如果是等待接单状态，应该先接单
        wx.showToast({
          title: '请先接单该订单',
          icon: 'none'
        })
        return
      case 'completed':
      case 'cancelled':
        wx.showToast({
          title: '订单已完成，无法继续更新',
          icon: 'none'
        })
        return
      default:
        console.log('❌ 当前状态不支持更新:', order.status)
        wx.showToast({
          title: `当前状态"${this.getStatusText(order.status)}"暂不支持更新`,
          icon: 'none'
        })
        return
    }
    
    console.log('📋 可选状态选项:', statusOptions)
    
    if (statusOptions.length === 0) {
      wx.showToast({
        title: '当前状态已是最终状态',
        icon: 'none'
      })
      return
    }
    
    wx.showActionSheet({
      itemList: statusOptions.map(item => item.name),
      success: (res) => {
        console.log('✅ 选择了状态，索引:', res.tapIndex)
        const selectedStatus = statusOptions[res.tapIndex]
        console.log('映射的状态值:', selectedStatus)
        
        this.setData({
          showStatusModal: true,
          statusForm: {
            orderId: order.id,
            status: selectedStatus.key,
            statusName: selectedStatus.name,
            notes: '',
            images: []
          }
        })
        
        console.log('📋 弹窗状态已设置:', this.data.showStatusModal)
      },
      fail: (error) => {
        console.log('❌ 状态选择取消或失败:', error)
      }
    })
  },

  // 关闭状态更新弹窗
  hideStatusModal() {
    this.setData({
      showStatusModal: false,
      statusForm: {
        orderId: '',
        status: '',
        statusName: '',
        notes: '',
        images: []
      }
    })
  },

  // 状态更新表单输入
  onStatusFormInput(e) {
    const { value } = e.detail
    this.setData({
      'statusForm.notes': value
    })
  },

  // 确认更新状态
  async confirmUpdateStatus() {
    console.log('🔄 开始确认更新状态 (列表页)')
    const { statusForm } = this.data
    
    console.log('📋 状态表单数据:', statusForm)
    
    if (!statusForm.status) {
      console.log('❌ 未选择状态')
      wx.showToast({
        title: '请选择状态',
        icon: 'none'
      })
      return
    }
    
    wx.showLoading({ title: '更新中...' })
    
    try {
      console.log('📡 准备调用云函数...')
      const result = await wx.cloud.callFunction({
        name: 'teamOrderManager',
        data: {
          action: 'updateOrderStatus',
          orderId: statusForm.orderId,
          status: statusForm.status,
          notes: statusForm.notes
        }
      })
      
      console.log('📡 云函数返回结果:', result)
      
      if (result.result.success) {
        wx.hideLoading()
        wx.showToast({
          title: '状态更新成功',
          icon: 'success'
        })
        
        this.hideStatusModal()
        
        // 刷新统计数据
        await this.loadOrderStats()
        
        // 刷新数据
        await this.refreshCurrentTab()
        
      } else {
        wx.hideLoading()
        wx.showToast({
          title: result.result.error || '更新失败',
          icon: 'none'
        })
      }
      
    } catch (error) {
      wx.hideLoading()
      console.error('更新状态失败:', error)
      wx.showToast({
        title: '网络错误',
        icon: 'none'
      })
    }
  },

  // 联系客户
  callCustomer(e) {
    const phone = e.currentTarget.dataset.phone
    
    if (!phone) {
      wx.showToast({
        title: '电话号码不存在',
        icon: 'none'
      })
      return
    }
    
    wx.makePhoneCall({
      phoneNumber: phone,
      fail: (error) => {
        console.error('拨打电话失败:', error)
        wx.showToast({
          title: '拨打失败',
          icon: 'none'
        })
      }
    })
  },

  // 筛选订单
  onFilterChange(e) {
    const { type, value } = e.currentTarget.dataset
    
    this.setData({
      [`filters.${type}`]: value
    })
    
    // 重新加载当前标签页数据
    this.refreshCurrentTab()
  },

  // 计算时间差（小时）
  calculateHours(timeStr) {
    if (!timeStr) return 0
    
    const time = new Date(timeStr)
    const now = new Date()
    const diff = now - time
    
    return Math.floor(diff / (1000 * 60 * 60))
  },

  // 格式化时间
  formatTime(timeStr) {
    if (!timeStr) return ''
    
    const date = new Date(timeStr)
    const now = new Date()
    const diff = now - date
    
    if (diff < 3600000) { // 1小时内
      const minutes = Math.floor(diff / 60000)
      return `${minutes}分钟前`
    } else if (diff < 86400000) { // 24小时内
      const hours = Math.floor(diff / 3600000)
      return `${hours}小时前`
    } else {
      return `${date.getMonth() + 1}/${date.getDate()}`
    }
  },

  // 获取紧急程度样式
  getUrgencyStyle(urgency) {
    const urgencyMap = {
      low: { color: '#52c41a', bgColor: '#f6ffed' },
      normal: { color: '#1890ff', bgColor: '#e6f7ff' },
      high: { color: '#fa8c16', bgColor: '#fff2e8' },
      urgent: { color: '#f5222d', bgColor: '#fff1f0' }
    }
    return urgencyMap[urgency] || urgencyMap.normal
  },

  // 获取状态样式
  getStatusStyle(status) {
    const statusMap = {
      waiting_team: { color: '#fa8c16', bgColor: '#fff2e8' },
      accepted: { color: '#1890ff', bgColor: '#e6f7ff' },
      surveying: { color: '#722ed1', bgColor: '#f9f0ff' },
      designing: { color: '#eb2f96', bgColor: '#fff0f6' },
      quoted: { color: '#13c2c2', bgColor: '#e6fffb' },
      in_progress: { color: '#fa541c', bgColor: '#fff2e8' },
      testing: { color: '#2f54eb', bgColor: '#f0f5ff' },
      completed: { color: '#52c41a', bgColor: '#f6ffed' }
    }
    return statusMap[status] || statusMap.waiting_team
  }
})
